// pages/Plan/PlanCard.jsx
import { CreateCustomerPortalSession, Subscribe } from "api/mutations";
import Loader from "components/atoms/Loader";
import { ENABLE_CUSTOMER_PORTAL } from "config";
import ConfirmAlert from "libs/confirmAlert";
import { formatMoney } from "libs/utils";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQueryClient } from "react-query";
import { useStripe } from '@stripe/react-stripe-js';
import QueryDebugLogger from 'components/debugging/QueryDebugLogger';
import {
  Card,
  CardHeader,
  CardContent,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Box
} from '@mui/material';
import CheckIcon from '@mui/icons-material/Check';
import { styled } from '@mui/material/styles';

// Styled components with business aesthetic
const BusinessCard = styled(Card)(({ theme }) => ({
  borderRadius: '8px',
  transition: 'all 0.3s ease',
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
  backgroundColor: 'white',
  boxShadow: '0 4px 15px rgba(0, 0, 0, 0.08)',
  position: 'relative',
  overflow: 'hidden',
  '&:hover': {
    transform: 'translateY(-5px)',
    boxShadow: '0 8px 25px rgba(0, 0, 0, 0.1)',
  },
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '4px',
    backgroundColor: '#40d47e',
  }
}));

const PlanTitle = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '1.5rem',
  fontWeight: '600',
  color: '#2d3748',
  marginBottom: theme.spacing(0.5),
  textAlign: 'center',
}));

const PriceContainer = styled(Box)(({ theme }) => ({
  textAlign: 'center',
  marginTop: theme.spacing(2),
  marginBottom: theme.spacing(3),
}));

const PlanPrice = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '2.5rem',
  fontWeight: '700',
  color: '#40d47e',
  lineHeight: 1.2,
  display: 'inline-block',
}));

const PriceCurrency = styled('span')(({ theme }) => ({
  fontSize: '1.5rem',
  fontWeight: '500',
  verticalAlign: 'top',
  color: '#40d47e',
  marginRight: '2px',
}));

const RecurringPeriod = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '0.95rem',
  color: '#718096',
  marginTop: theme.spacing(0.5),
}));

const BusinessButton = styled(Button)(({ theme, disabled }) => ({
  backgroundColor: disabled ? '#e2e8f0' : '#40d47e',
  color: disabled ? '#a0aec0' : 'white',
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontWeight: '500',
  padding: '10px 16px',
  textTransform: 'none',
  borderRadius: '6px',
  boxShadow: disabled ? 'none' : '0 4px 10px rgba(64, 212, 126, 0.25)',
  transition: 'all 0.3s ease',
  '&:hover': {
    backgroundColor: disabled ? '#e2e8f0' : '#36bc6f',
    boxShadow: disabled ? 'none' : '0 6px 15px rgba(64, 212, 126, 0.35)',
    transform: disabled ? 'none' : 'translateY(-2px)',
  }
}));

const StyledCardHeader = styled(CardHeader)(({ theme }) => ({
  paddingBottom: 0,
  paddingTop: theme.spacing(3),
  '& .MuiCardHeader-content': {
    width: '100%',
  }
}));

const StyledCardContent = styled(CardContent)(({ theme }) => ({
  padding: theme.spacing(2, 3, 3),
  flexGrow: 1,
  display: 'flex',
  flexDirection: 'column',
}));

const StyledList = styled(List)(({ theme }) => ({
  padding: 0,
  marginBottom: theme.spacing(3),
  flexGrow: 1,
}));

const StyledListItem = styled(ListItem)(({ theme }) => ({
  padding: theme.spacing(0.75, 0),
}));

const StyledListItemText = styled(ListItemText)(({ theme }) => ({
  '& .MuiListItemText-primary': {
    fontSize: '0.95rem',
    color: '#4a5568',
  }
}));

const StyledCheckIcon = styled(CheckIcon)(({ theme }) => ({
  color: '#40d47e',
  fontSize: '1.25rem',
}));

const BusinessDialog = styled(Dialog)(({ theme }) => ({
  '& .MuiDialog-paper': {
    borderRadius: '8px',
    boxShadow: '0 10px 30px rgba(0, 0, 0, 0.1)',
    overflow: 'hidden',
  }
}));

const DialogTitleStyled = styled(DialogTitle)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '1.25rem',
  fontWeight: '600',
  color: '#2d3748',
  borderBottom: '1px solid #e2e8f0',
  padding: theme.spacing(2, 3),
}));

const DialogContentStyled = styled(DialogContent)(({ theme }) => ({
  padding: theme.spacing(3),
  color: '#4a5568',
  fontSize: '1rem',
}));

const DialogActionsStyled = styled(DialogActions)(({ theme }) => ({
  padding: theme.spacing(2, 3),
  borderTop: '1px solid #e2e8f0',
}));

const LoaderContainer = styled(Box)(({ theme }) => ({
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  minHeight: '300px',
}));

const PlanCard = ({
  plan,
  monthly,
  setSelectedPlan,
  currentSubscription,
  cardsData,
}) => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [confirmDialog, setConfirmDialog] = useState(false);
  const [debugVisible, setDebugVisible] = useState(false);
  const [isSubscribing, setIsSubscribing] = useState(false);
  const queryClient = useQueryClient();
  const stripe = useStripe();

  const mutation = useMutation(Subscribe);
  const customerPortalSessionMutate = useMutation(CreateCustomerPortalSession);

  const redirectToCustomerPortalSession = async () => {
    const response = await customerPortalSessionMutate.mutateAsync();
    window.location.href = response.data.redirect_url;
  };

  const handleSuccess = (message = t("planCard.planUpdated")) => {
    queryClient.invalidateQueries(["Me"]);
    ConfirmAlert.success(message);
    setTimeout(() => {
      window.location.href = "/dashboard";
    }, 3000);
  };

  const onUpdatePlanSubmit = async (planId) => {
    if (!stripe) {
      return;
    }

    try {
      setLoading(true);
      setIsSubscribing(true); // Set subscribing state
      setDebugVisible(true); // Show debug logger only when subscribing/updating
      
      const response = await mutation.mutateAsync({ 
        planId,
        planType: plan.planType // Add planType from plan prop
      });

      if (response.data.latest_invoice.payment_intent?.client_secret) {
        const { error } = await stripe.confirmCardPayment(
          response.data.latest_invoice.payment_intent.client_secret,
          {
            setup_future_usage: "off_session",
          }
        );

        if (error) {
          throw new Error(error.message);
        }
        handleSuccess();
      } else if (response.data.latest_invoice.paid) {
        handleSuccess();
      } else {
        handleSuccess(response.data.message);
      }
    } catch (error) {
      console.log("error ---- ", error);
      ConfirmAlert.error(t("stripeForm.paymentFailed"));
      // setTimeout(() => {
      //   window.location.href = "/dashboard";
      // }, 3000);
      setLoading(false);
      // Don't reset isSubscribing - keep debug logger visible even on error
    }
  };

  const handlePlanUpdate = (planId) => {
    if (ENABLE_CUSTOMER_PORTAL) {
      return redirectToCustomerPortalSession();
    }
    setConfirmDialog(true);
  };

  const renderButton = () => {
    if (!currentSubscription) {
      return (
        <BusinessButton
          fullWidth
          onClick={() => setSelectedPlan(plan.id)}
        >
          {t("planCard.selectPlan")}
        </BusinessButton>
      );
    }

    const isCurrentPlan = currentSubscription.plan.id === plan.id;
    const isActive = currentSubscription.status === "active";
    const isPastDue = currentSubscription.status === "past_due";
    const isIncomplete = currentSubscription.status === "incomplete";

    if (isCurrentPlan && isActive) {
      return (
        <BusinessButton fullWidth disabled>
          {t("planCard.currentPlan")}
        </BusinessButton>
      );
    }

    if (isCurrentPlan && isPastDue) {
      return (
        <BusinessButton fullWidth>
          {t("planCard.toPay")}
        </BusinessButton>
      );
    }

    if (isActive || isIncomplete) {
      return (
        <BusinessButton
          fullWidth
          onClick={() => cardsData.length === 0 
            ? setSelectedPlan(plan.id)
            : handlePlanUpdate(plan.id)
          }
        >
          {t("planCard.changePlan")}
        </BusinessButton>
      );
    }
  };

  // Format and split the price for better formatting
  const formattedPrice = formatMoney("it", plan.currency, plan.price);
  const [currency, price] = formattedPrice.match(/^([€$£])\s*(.*)$/)?.slice(1) || ['', formattedPrice];

  // Prepare queries for debug logger
  const queriesForDebug = [
    {
      name: "Subscribe Mutation",
      isLoading: mutation.isLoading,
      isError: mutation.isError,
      error: mutation.error,
      data: mutation.data
    },
    {
      name: "Plan Data",
      isLoading: false,
      isError: false,
      data: {
        planId: plan.id,
        planType: plan.planType,
        title: plan.title,
        price: plan.price,
        currency: plan.currency,
        monthly: monthly,
        features: plan.features
      }
    },
    {
      name: "Component State",
      isLoading: false,
      isError: false,
      data: {
        loading,
        confirmDialog,
        debugVisible,
        isSubscribing,
        currentSubscription
      }
    }
  ];

  return (
    <>
      <BusinessCard>
        {loading ? (
          <LoaderContainer>
            <Loader />
          </LoaderContainer>
        ) : (
          <>
            <StyledCardHeader
              title={
                <PlanTitle>
                  {plan.title}
                </PlanTitle>
              }
            />
            <StyledCardContent>
              <PriceContainer>
                <PlanPrice>
                  <PriceCurrency>{currency}</PriceCurrency>{price}
                </PlanPrice>
                <RecurringPeriod>
                  {monthly ? t("planCard.month") : t("planCard.year")}
                </RecurringPeriod>
              </PriceContainer>
              
              <StyledList>
                {plan.features.map((feature, i) => (
                  <StyledListItem key={`feature-${i}`} disableGutters>
                    <ListItemIcon sx={{ minWidth: '32px' }}>
                      <StyledCheckIcon />
                    </ListItemIcon>
                    <StyledListItemText primary={t(feature)} />
                  </StyledListItem>
                ))}
              </StyledList>
              
              {renderButton()}
            </StyledCardContent>
          </>
        )}
      </BusinessCard>

      <BusinessDialog
        open={confirmDialog}
        onClose={() => setConfirmDialog(false)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitleStyled>
          {t("planCard.updateSubscription")}
        </DialogTitleStyled>
        <DialogContentStyled>
          {t("planCard.areYouSure")}
        </DialogContentStyled>
        <DialogActionsStyled>
          <Button 
            onClick={() => setConfirmDialog(false)}
            sx={{ 
              color: '#4a5568',
              textTransform: 'none',
              fontWeight: 500
            }}
          >
            {t("planCard.no")}
          </Button>
          <BusinessButton
            onClick={() => {
              setConfirmDialog(false);
              onUpdatePlanSubmit(plan.id);
            }}
            sx={{ boxShadow: 'none' }}
          >
            {t("planCard.yes")}
          </BusinessButton>
        </DialogActionsStyled>
      </BusinessDialog>
      
      <QueryDebugLogger queries={queriesForDebug} isVisible={debugVisible && isSubscribing} />
    </>
  );
};

export default PlanCard;